<script lang="ts">
    import { searchBooks, addCopies, removeCopies, removeBook } from "./api/api";
    import type { BookRecord } from "./api/book-record";

    let email = $state("");
    let password = $state("");

    // Book management state
    let titleFilter = $state("");
    let authorFilter = $state("");
    let isbnFilter = $state("");
    let availableFilter: boolean | undefined = $state(undefined);

    let currentPage = $state(0);
    let pageSize = 10;
    let sortField = 'id';
    let sortDirection: 'desc' | 'asc' | undefined = 'desc';

    let books: BookRecord[] = $state([]);
    let totalPages = $state(0);

    function getPages() {
        return Array.from({ length: totalPages }, (_, i) => i);
    }

    async function loadBooks() {
        const userInfo = { email, password };
        const response = await searchBooks(titleFilter, authorFilter, isbnFilter, availableFilter, currentPage, pageSize, sortField, sortDirection, userInfo);
        if (response.data?.success && response.data.data) {
            books = response.data.data.content || [];
            totalPages = Math.ceil((books.length || 1) / pageSize);
        }
    }

    async function handleAddCopies(bookId: number) {
        const copiesToAdd = parseInt(prompt("Enter number of copies to add:", "1") || "1", 10);
        if (!isNaN(copiesToAdd) && copiesToAdd > 0) {
            const userInfo = { email, password };
            await addCopies({ bookId, copies: copiesToAdd }, userInfo);
            await loadBooks();
        }
    }

    async function handleRemoveCopies(bookId: number) {
        const copiesToRemove = parseInt(prompt("Enter number of copies to remove:", "1") || "1", 10);
        if (!isNaN(copiesToRemove) && copiesToRemove > 0) {
            const userInfo = { email, password };
            await removeCopies({ bookId, copies: copiesToRemove }, userInfo);
            await loadBooks();
        }
    }

    function goToPage(page: number) {
        currentPage = page;
        loadBooks();
    }

    async function handleRemoveBook(bookId: number) {
        const userInfo = { email, password };
        if (!confirm("Are you sure you want to remove this book?")) {
            return;
        }
        await removeBook(bookId, userInfo);
        await loadBooks();
    }
</script>

<style>

</style>

<div class="max-w-4xl mx-auto mt-10 p-6 bg-white rounded-xl shadow-md">
    <h2 class="text-2xl font-bold text-gray-800 mb-6">Manage Books</h2>

    <div class="mb-6 p-4 bg-gray-50 rounded-lg">
        <h3 class="text-lg font-medium text-gray-700 mb-4">Login Credentials</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
                <label for="email" class="block text-sm font-medium text-gray-700 mb-1">Email</label>
                <input type="text" id="email" bind:value={email} 
                    class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
                <label for="password" class="block text-sm font-medium text-gray-700 mb-1">Password</label>
                <input type="password" id="password" bind:value={password}
                    class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
        </div>
    </div>

    <div class="mb-6">
        <h3 class="text-lg font-medium text-gray-700 mb-4">Search Filters</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div>
                <label for="title" class="block text-sm font-medium text-gray-700 mb-1">Title</label>
                <input type="text" id="title" bind:value={titleFilter}
                    class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
                <label for="author" class="block text-sm font-medium text-gray-700 mb-1">Author</label>
                <input type="text" id="author" bind:value={authorFilter}
                    class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
                <label for="isbn" class="block text-sm font-medium text-gray-700 mb-1">ISBN</label>
                <input type="text" id="isbn" bind:value={isbnFilter}
                    class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
                <label for="available" class="block text-sm font-medium text-gray-700 mb-1">Available</label>
                <select id="available" bind:value={availableFilter}
                    class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                    <option value={null}>All</option>
                    <option value={true}>Yes</option>
                    <option value={false}>No</option>
                </select>
            </div>
        </div>
        <div class="mt-4">
            <button on:click={() => loadBooks()}
                class="w-full py-2 px-4 bg-indigo-600 text-white font-semibold rounded-md shadow hover:bg-indigo-700 transition duration-200">
                Search
            </button>
        </div>
    </div>

    <div class="flex justify-center mb-6">
        <nav class="inline-flex space-x-2">
            <button on:click={() => goToPage(currentPage - 1)} disabled={currentPage === 0}
                class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 transition duration-200 flex items-center">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clip-rule="evenodd" />
                </svg>
                Previous
            </button>

            {#each getPages() as pages}
                {#each [pages] as page}
                    <button on:click={() => goToPage(page)}
                        class="px-4 py-2 {page === currentPage ? 'bg-indigo-600 text-white' : 'bg-gray-200 text-gray-700 hover:bg-gray-300'} rounded-md transition duration-200">
                        {page + 1}
                    </button>
                {/each}
            {/each}

            <button on:click={() => goToPage(currentPage + 1)} disabled={currentPage >= totalPages - 1}
                class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 transition duration-200 flex items-center">
                Next
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 ml-1" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd" />
                </svg>
            </button>
        </nav>
    </div>

    {#if books.length > 0}
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Title</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Author</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ISBN</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Copies Available</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    {#each books as book (book.id)}
                        {#if typeof book.id !== 'undefined'}
                            <tr class="hover:bg-gray-50 transition duration-150 ease-in-out">
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{book.id}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{book.title}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{book.author}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{book.isbn}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{book.availableCopies}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium space-x-2">
                                    <button on:click={() => handleAddCopies(book.id!)}
                                        class="text-indigo-600 hover:text-indigo-900 transition duration-150 ease-in-out">
                                        Add Copies
                                    </button>
                                    <button on:click={() => handleRemoveCopies(book.id!)}
                                        class="text-red-600 hover:text-red-900 transition duration-150 ease-in-out">
                                        Remove Copies
                                    </button>
                                    <button on:click={() => handleRemoveBook(book.id!)} disabled={book.availableCopies !== 0}
                                        class="text-red-600 hover:text-red-900 transition duration-150 ease-in-out">
                                        Remove Book
                                    </button>
                                </td>
                            </tr>
                        {/if}
                    {/each}
                </tbody>
            </table>
        </div>
    {/if}
</div>